<?php

namespace app\common\validate\knowbase;

use think\Validate;

class Project extends Validate
{
    /**
     * 验证规则
     */
    protected $rule = [
        'title' => 'require|checkParams',
    ];
    /**
     * 提示消息
     */
    protected $message = [
    ];
    /**
     * 验证场景
     */
    protected $scene = [
        'add'  => [],
        'edit' => [],
    ];

    /**
     * 检查所有表单参数
     * @param $value
     * @param $rule
     * @param $data
     * @param $field
     * @param $title
     * @return bool|int|mixed|string|null
     */
    protected function checkParams($value, $rule, $data, $field, $title)
    {
        if (isset($data['identify']) && $data['identify']) {
            $config = get_addon_config('knowbase');
            $projects = array_values(array_filter($config['rewrite'],function ($key){
                return strpos($key,'index/project')!==false;
            },ARRAY_FILTER_USE_KEY));
            if(array_filter($projects,function ($v) use($data){
                return strpos($v, '/'.$data['identify'])!==false;
            })) {
                return __('error_identify_keyword',$data['identify']);
            } else if (is_numeric($data['identify'])) {
                return __('error_identify_number');
            }
            $id = request()->param('ids','');
            if ($id) {
                $row = \app\common\model\knowbase\Project::where('id', '<>', $id)->where('identify', $data['identify'])->find();
            } else {
                $row = \app\common\model\knowbase\Project::where('identify', $data['identify'])->find();
            }
            if ($row) {
                return __('error_identify_exist');
            }
        }
        return true;
    }

}
